import React from 'react';
import { withRouter } from 'react-router-dom'
import Toast from '../../commponents/toast'
import axios from 'axios'
import SelfCenter from '../../commponents/SelfPage/index'
import logo from '../../assets/Mine/logo.png'
import './mine.css'
import '../../assets/font_0nudkwzee6x9/iconfont.css'
import {getPhoneCode} from '../../api/api'
import toast from '../../commponents/toast';

class Tab extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            tabs:[
                {tabName:"验证码登陆",id:1},
                {tabName:"密码登陆",id:2},
            ],
            pwdLogin:false,  //是否用密码登录
            currentIndex:1,
            isShow:true,   //用于密码是否可见
            type:true,      //文本框显示类型，true为密码库那个，false为普通文本框
            isVerticateShow:false, //用于显示验证码是否亮起
            phoneNumInputBorderColor:false, //用于显示手机号码输入框失去焦点和获得焦点后的边框，false为不显                                   示，true为显示
            confirmInputBorderColor:false,//用于显示短信验证码输入框失去焦点和获得焦点后的边框，false为不显                                 示，true为显示
            confirmInnerText:'获取验证码', // 用于获取验证码的内容填充
            userInput:false,      //用于显示用户名获取焦点和失去焦点
            passwordInput:false,   //用于显示用户密码得到家电和失去焦点
            vertivalInput:false,   //用于验证码输入框获得焦点和失去焦点
            countDownStatus:false,  //开关，用于判断是否在倒计时
            isBtnClicked:true,      //获取验证码按钮是否可点击
            userPhone:'',            //用户手机号
            smsCode:'', //用户短信验证码
            isLogin:false,//登录状态
            userName:'',//用户名
            userPwd:'',//用户密码
            userCode:'',//验证码
            loginedUserName:''
        };
    }
    componentDidMount() {

    }
    tabChoiced=(id)=>{
        //tab切换到方法
        this.setState({
            currentIndex:id
        });
    }
    //密码可见与不可见的切换
    switchIcon=()=>{
        this.setState({
            isShow:!this.state.isShow,
            type:!this.state.type
        })
        // console.log(this.isShow)
    }
    //手机账号输入框获得焦点
    onPhoneNumFocus=()=>{
        this.setState({
            inputBorderColor:true
        })
    }
    //手机账号输入框失去焦点
    onPhoneNumBlur=()=>{
        this.setState({
            inputBorderColor:false
        })
    }
    //短信验证码输入框获得焦点
    onConfirmNumFocus=()=>{
        this.setState({
            confirmInputBorderColor:true
        })
    }
    //短信验证码输入框失去焦点
    onConfirmNumBlur=(e)=>{
        this.setState({
            confirmInputBorderColor:false
        })
        //短信验证码格式验证
        let smsCode =/^\d{6}$/;
        if(!smsCode.test(e.target.value)||e.target.value ===''){
            Toast.error('请输入正确的验证码',2000)
        }else{
            this.setState({
                smsCode:e.target.value
            })
        }
    }

    onUserFocus=()=>{
        this.setState({
            userInput:true
        })
    }
    onUserBlur=(event)=>{
        let reg = /[\s\S]*/;
        if(!reg.test(event.target.value||event.target.value ==='')){
            Toast.error('用户名不能为空',2000)
        }else{
            this.setState({
                userInput:false,
                userName:event.target.value
            })
        }   
    }
    onPwdFocus=()=>{
        this.setState({
            passwordInput:true
        })
    }
    onPwdBlur=(e)=>{
        this.setState({
            passwordInput:false,
            userPwd:e.target.value
        })
    }
    onVertivalFocus=()=>{
        this.setState({
            vertivalInput:true
        })
    }
    onVertivalBlur=(e)=>{
        this.setState({
            vertivalInput:false,
            userCode:e.target.value
        });
        if(e.target.value === ''){
            Toast.error('验证码不能为空',2000)
        }
    }

    //svg验证码替换
    getSvg=()=>{
        axios({
            url:'http://127.0.0.1:3000/api/captcha',
            method:'get'
        }).then(res=>{
            //将请求下来的svg重新赋值到img标签的src属性中
            this.refs.mySvg.src=`http://127.0.0.1:3000/api/captcha?time=${new Date().getTime()}`
        })
    }

    //手机号验证规则
    phoneNumConfirm=(event)=>{
        let phoneReg = /^1[34578]\d{9}$/;
        if(phoneReg.test(event.target.value)){
            this.setState({
                isVerticateShow:true,
                isBtnClicked:false,
                userPhone:event.target.value
            })
        }else{
            this.setState({
                isVerticateShow:false,
                isBtnClicked:true
            })
        }
    }
    //模拟短信验证码发送时间
    simulateTime=(lower,upper)=>{
        let choices = upper - lower;
        return Math.floor(Math.random() * choices + lower);
    }
    //获取短信验证码
    getSmsUtil=(e)=>{
        //1.判断手机号是否输入完整
        if(!this.state.isVerticateShow){
            Toast.error('请输入正确的手机号',2000)
        }
        //2.设置获取验证码倒计时
        var count = 59;
        var timer = setInterval(()=>{
            this.setState({
                confirmInnerText:`重新获取(${count--})`,
                isBtnClicked:true  //倒计时期间不允许再次点击获取验证码按钮
            })
            //3.倒计时结束，回归到以前的状态
            if(this.state.isLogin){
                clearInterval(timer);
                return;
            }
            if(count === -1){
                clearInterval(timer);

                this.setState({
                    confirmInnerText:`获取验证码`,
                    isBtnClicked:false
                })
            }
        },1000);
        
        //4.获取短信验证码
        axios.get('http://localhost:3000/api/send_code',{
            params: {
                phone: this.state.userPhone
             }
        }).then(res=>{
            //5.短信验证码获取成功
            if(res.data.success_code==200){
                setTimeout(()=>{
                    Toast.info('验证码为:'+res.data.message,5000)
                // },this.simulateTime(5000,8000))
                },2000)
            }else{
                //6.短信验证码获取失败
                setTimeout(()=>{
                    Toast.error('验证码获取失败，请重试',5000);
                    clearInterval(timer);
                    this.setState({
                        confirmInnerText:`获取验证码`,
                        isBtnClicked:false
                    })
                },2000);

            }
        })

    }
    //短信验证码登陆
    loginByCode=()=>{
        axios.post('http://localhost:3000/api/login_code',{
            params:{
                phone: this.state.userPhone,
                code:  this.state.smsCode
            }
        }).then(res=>{
            if(res.data.success_code){
                // this.props.history.push({
                //     pathname:'/',
                // })
                // console.log(res.data.message.user_name)
                Toast.info('登录成功',2000);
                this.setState({
                    isLogin:true,
                    loginedUserName:res.data.message.user_name
                });
                sessionStorage.setItem('isLogin',this.state.isLogin)
            }else{
                Toast.info('用户名或密码错误',2000)
            }
        })
    }
    // handlerChange=(e)=>{
    //     this.setState({
    //         userName:e.target.value
    //     })
    //     console.log(this.state.userName)
    // }
    //密码登录
     loginByPwd=()=>{
        let { userName, userPwd, userCode } = this.state;
        if(userName === ''){
            Toast.error('请输入用户名',2000);
            return;
        }
        if(userPwd === ''){
            Toast.error('请输入密码',2000);
            return;
        }
        if(userCode === ''){
            Toast.error('请输入验证码',2000);
            return;
        }
        axios.post('http://localhost:3000/api/login_pwd',{
            params:{
                user_name:this.state.userName,
                user_pwd:this.state.userPwd
            }
        }).then(res=>{
            if(res.data.success_code){
                
                this.setState({
                    isLogin:true
                });
                // console.log(this.state.isLogin)
                sessionStorage.setItem('isLogin',this.state.isLogin)
                Toast.info('登录成功',2000);
            }else{
                Toast.info(res.data.message,2000);
            }
        })
    }

    // componentDidMount(){
    //     console
    // }

    render(){
        if(sessionStorage.getItem('isLogin')===null||sessionStorage.getItem('isLogin')===false){
        let _this=this;
        let isBox1Show=this.state.currentIndex===1 ? 'block' : 'none';
        let isBox2Show=this.state.currentIndex===2 ? 'block' : 'none';

        let tabList= this.state.tabs.map(function(res,index) {
              // 遍历标签页，如果标签的id等于tabid，那么该标签就加多一个active的className
              let tabStyle=res.id===this.state.currentIndex ? 'subCtrl active' : 'subCtrl';

            return    <li key={index} onClick={this.tabChoiced.bind(_this,res.id)} className={tabStyle}>{res.tabName}</li>

        }.bind(_this));
        return (
            <div className="tab-container">
                <img className='mine-logo' src={logo} alt='' style={{'marginBottom':'30px'}}/>
                <ul className="tab-header">
                    {tabList}
                </ul>
                <div className="tab-content">
                    <div style={{"display":isBox1Show}}  className='verification-login-block'>
                        <div className='phone-input' style={{'border':this.state.inputBorderColor?'1px solid #11b57c':'1px solid rgb(230,230,230)'}}>
                            <input
                                type='text'
                                placeholder='请输入手机号'
                                onKeyUp={this.phoneNumConfirm.bind(this)}
                                onFocus={this.onPhoneNumFocus.bind(this)}
                                onBlur={this.onPhoneNumBlur.bind(this)}
                            />
                            <button
                                style={{'color':(this.state.isVerticateShow)?'#11b57c':'rgb(230,230,230)',
                                'pointerEvents':(this.state.isBtnClicked)?'none':'auto'}}
                                onClick={this.getSmsUtil.bind(this)}

                            >{this.state.confirmInnerText}</button>
                        </div>
                        <div className='verification-input' style={{'border':this.state.confirmInputBorderColor?'1px solid #11b57c':'1px solid rgb(230,230,230)'}}>
                            <input
                                type='text'
                                placeholder='请输入验证码'
                                onFocus={this.onConfirmNumFocus.bind(this)}
                                onBlur={this.onConfirmNumBlur.bind(this)}
                                maxLength='6'
                            />
                        </div>
                        <div className='agreement'>温馨提示：未注册易果生鲜账号的手机号，登录时将自动注册，且代表已同意<span> 服务协议与隐私政策 </span></div>
                        <button 
                            className='login-system' 
                            onClick={this.loginByCode}
                            style={{'marginTop':'20px'}}>登录</button>
                        <button className='back-to-mine'>返回</button>
                    </div>
                    <div style={{"display":isBox2Show}} className='password-login-block'>
                        <div className='user-input'
                             style={{'border':this.state.userInput?'1px solid #11b57c':'1px solid rgb(230,230,230)'}}>
                            <input  type='text' placeholder='用户名/手机号'
                                    onFocus = {this.onUserFocus.bind(this)}
                                    onBlur = {this.onUserBlur.bind(this)}
                                    onChange = {this.handlerChange}
                                    />
                        </div>
                        <div
                            className='password-input'
                            style={{'border':this.state.passwordInput?'1px solid #11b57c':'1px solid rgb(230,230,230)'}}>
                            <input
                                type={this.state.type?'password':'text'}
                                placeholder='密码'
                                onFocus = {this.onPwdFocus.bind(this)}
                                onBlur = {this.onPwdBlur.bind(this)}
                                />
                            <span
                                className={this.state.isShow?'iconfont icon-mimabukejian':'iconfont icon-mimakejian'}
                                onClick={this.switchIcon.bind(this)}
                            ></span>
                        </div>
                        <div
                            className='confirm-input'
                            style={{'border':this.state.vertivalInput?'1px solid #11b57c':'1px solid rgb(230,230,230)'}}>
                            <input
                                type='text'
                                placeholder='验证码'
                                onFocus = {this.onVertivalFocus.bind(this)}
                                onBlur = {this.onVertivalBlur.bind(this)}/>
                            <div
                                className='code-svg'
                                style={{'float':'right','height':'100%','width':'131px'}}>
                                <img
                                    ref='mySvg'
                                    style={{'height':'100%'}}
                                    onClick={this.getSvg}
                                    src={'http://localhost:3000/api/captcha'} alt=''/>
                            </div>
                        </div>
                        <button className='login-system' style={{'marginTop':'22px'}} onClick={this.loginByPwd}>登录</button>
                        <button className='back-to-mine'>返回</button>
                    </div>
                </div>
            </div>
        )
    }else{

        return(
            <SelfCenter userName={this.state.loginedUserName}/>
        )
    }
    }
}

export default withRouter(Tab);